"""数据库核心模块

基于Peewee ORM的数据库连接和管理
提供数据库初始化、连接管理等功能
使用MySQL数据库，支持连接池管理
"""

import os
from peewee import *
from playhouse.pool import PooledMySQLDatabase
from loguru import logger
from app.config import settings


# MySQL数据库连接池
database = PooledMySQLDatabase(
    settings.db_name,
    user=settings.db_user,
    password=settings.db_password,
    host=settings.db_host,
    port=settings.db_port,
    charset='utf8mb4',
    max_connections=settings.db_max_connections,
    stale_timeout=settings.db_stale_timeout,
    timeout=settings.db_timeout,
    connect_timeout=settings.db_connect_timeout
)
logger.info(f"使用MySQL连接池: {settings.db_host}:{settings.db_port}/{settings.db_name}, 最大连接数: {settings.db_max_connections}")


class BaseModel(Model):
    """基础模型类
    
    所有数据模型的基类
    提供通用的数据库配置和方法
    """
    
    class Meta:
        database = database
        legacy_table_names = False


def init_database() -> bool:
    """初始化数据库连接
    
    Returns:
        bool: 初始化是否成功
    """
    try:
        database.connect()
        logger.info(f"数据库连接成功: {settings.db_host}:{settings.db_port}/{settings.db_name}")
        return True
    except Exception as e:
        logger.error(f"数据库连接失败: {str(e)}")
        return False


def close_db():
    """关闭数据库连接"""
    try:
        if not database.is_closed():
            database.close()
            logger.info("数据库连接已关闭")
    except Exception as e:
        logger.error(f"关闭数据库连接失败: {str(e)}")


def create_tables(models: list):
    """创建数据表
    
    Args:
        models: 数据模型列表
    """
    try:
        database.create_tables(models, safe=True)
        logger.info(f"数据表创建成功，共 {len(models)} 个表")
    except Exception as e:
        logger.error(f"创建数据表失败: {str(e)}")
        raise


def drop_tables(models: list):
    """删除数据表
    
    Args:
        models: 数据模型列表
    """
    try:
        database.drop_tables(models, safe=True)
        logger.info(f"数据表删除成功，共 {len(models)} 个表")
    except Exception as e:
        logger.error(f"删除数据表失败: {str(e)}")
        raise